// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import Item from "./Item";

const { ccclass, property } = cc._decorator;



@ccclass
export default class Rank extends cc.Component {

    @property(cc.Prefab)
    itemPrefab: cc.Prefab = null;
    @property(cc.Node)
    content: cc.Node = null;
    //存放玩家数据
    public allInfoList: any[];

    @property(cc.Node)
    canvas: cc.Node = null;

    opened:boolean = false;

    public Close() {

        this.opened = false;
        this.hideRank();
        this.canvas.active = false;
        
    }

    onLoad() {

        var _this = this;
        _this.canvas.active = false;
 
        wx.onMessage(data => {
            switch (data.message) {
                case 'Show':
                    _this.allInfoList = [];
                    _this.showRank();
                    break;
                case 'Hide':
                    _this.hideRank();
                    break;
                case 'RefreshMaxScore':
                    _this.UpdateScore(data.maxScore, data.watermellonNum);
            }
        });
    }
    UpdateScore(maxscore: string, water: string) {
        wx.getUserCloudStorage({

            keyList: ['maxScore', 'maxMellon'],

            success: function (res) {

                console.log(res);
                console.log(res.KVDataList);
                if (res.KVDataList == null || res.KVDataList.length<=0 || parseInt(res.KVDataList[0]['value']) < parseInt(maxscore)) {

                        wx.setUserCloudStorage({
                            KVDataList: [
                                { key: 'maxScore', value: maxscore },
                                { key: 'maxMellon', value: water }
                            ],
                            success(res): void {
                                console.log("成功托管最大分数：" + maxscore);
                                console.log(res);
                            },
                            fail(res): void {
                                console.log("最高分数托管失败：" + res);
                                console.log(res);
                            }
                        })
                }
            },
            fail: function () {
                console.log("失败：==========");
            }
        })

    }
    showRank() {


        if(this.opened)return;

        var _this = this;
        _this.opened = true;

        wx.getFriendCloudStorage({

            keyList: ['maxScore', 'maxMellon'],

            success: function (res) {

                console.log("成功：" + res);//同玩好友用户信息、分数
                console.log(res.data);//同玩好友用户信息、分数

                // for(var i = 0; i < res.data.length; i++){
                //     let item = cc.instantiate(_this.item);
                //     item.setParent(_this.itemParent);
                //     console.log("==========");
                //     console.log(res.data[i].nickname);
                //     item.getComponent(Item).InitItem(res.data[i].avatarUrl,res.data[i].nickname, res.data[i].KVDataList[1]['maxMellon'],res.data[i].KVDataList[0]['maxScore'])
                // }
                for (let i = 0; i < res.data.length; i++) {
                    // 获取玩家微信名，头像url和分数
                    let nickName = res.data[i].nickname;
                    let avatarUrl = res.data[i].avatarUrl;
                    let score = 1;
                    let watermelloNum = 1;

                    score = res.data[i].KVDataList[0]['value'];
                    watermelloNum = res.data[i].KVDataList[1]['value'];

                    console.log(watermelloNum);

                    // 加入到数组中
                    _this.allInfoList.push({
                        "nickName": nickName,
                        "avatarUrl": avatarUrl,
                        "score": score,
                        "watermelloNum": watermelloNum
                    });
                }
                _this.makeRanks();

            },
            fail: function () {
                console.log("失败：==========");
            }
        })
    }
    makeRanks() {
        // 首先将allInfoList内部元素进行排序，根据分数来降序排列
        this.allInfoList.sort((a, b) => {
            return b['score'] - a['score'];
        });
        console.log(this.allInfoList);
        // 根据各个玩家的分数制作排名
        for (let i = 0; i < this.allInfoList.length; i++) {
            let nickName = this.allInfoList[i]['nickName'];
            let avatarUrl = this.allInfoList[i]['avatarUrl'];
            let score = this.allInfoList[i]['score'];
            let watermelloNum = this.allInfoList[i]['watermelloNum'];

            this.createItem(watermelloNum, nickName, avatarUrl, score);
        }
        this.canvas.active = true;
    }

    // OpenData.js
    createItem(watermelloNum, nickName, avatarUrl, score) {
        // 生成item
        let item = cc.instantiate(this.itemPrefab);
        item.getComponent(Item).InitItem(avatarUrl, nickName, watermelloNum, score)
        // 添加到content中
        this.content.addChild(item);
    }

    hideRank() {
        for (var i = 0; i < this.content.childrenCount; i++) {

            this.content.children[i].destroy();
        }
    }
}
